package com.qf.air.interceptor;

import com.qf.air.constants.AirConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 维多利加
 * @Date: 2021/3/25 19:20
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //前处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 1. 从session中查询用户信息
         *  User user = (User) request.getSession().getAttribute("user");
         */

        //1. 从Redis中查询用户信息
        //1.1 获取Cookie中的userKey信息
        String keySuffix = null;
        String value = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (AirConstants.USER_COOKIE.equals(cookie.getName())) {
                    // 找到了匹配要求的cookie
                    keySuffix = cookie.getValue();
                    break;
                }
            }
        }


        //1.2 不为null,查询Redis
        if (!StringUtils.isEmpty(keySuffix)) {
//            传统Jedis操作
//            value = jedisUtil.get(AirConstants.USER_REDIS_PREFIX + keySuffix);
            value = stringRedisTemplate.opsForValue().get(AirConstants.USER_REDIS_PREFIX + keySuffix);
        }

        //2.如果登录了，return true，如果没登陆 return false
        if (value != null) {
//            传统Jedis操作
//            jedisUtil.expire(AirConstants.USER_REDIS_PREFIX + keySuffix,AirConstants.USER_TIMEOUT);
            stringRedisTemplate.expire(AirConstants.USER_REDIS_PREFIX + keySuffix,AirConstants.USER_TIMEOUT, TimeUnit.SECONDS);
            return true;
        } else {
            response.sendRedirect(request.getContextPath() + "/login.html");
            return false;
        }
    }

}
